package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.core.utils.EmptyUtility;
import com.honey.mybatis.generator.MybatisPlugin;

public class SelectByPrimaryKey extends AbstractMybatisMapper{

	public SelectByPrimaryKey(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		List<TableColumn> list = null;
		
		if( schema instanceof Table ){
			IntrospectTableColumn introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
			if( EmptyUtility.isListEmpty(introspectTableColumn.primaryKeyColumns()))
				return ;
			else
				list = introspectTableColumn.primaryKeyColumns();
		}
		
		parent.addNewLine();
		parent.addComments(
				"按照主键查询一条记录(包括大字段)"
		);
		String var_entity_name =  super.getEntityPrimitiveClassName(schema);
		XmlElement select = new XmlElement(parent,"select")
		.addAttribute("id",MapperConstant.SELECT_BY_PRIMARY_KEY_MAPPER_ID)
		//.addAttribute("resultMap",var_entity_name+mybatisPlugin.getBlobSuffix())
		.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
		.addAttribute("flushCache", "false")
		.addTextElement("SELECT ")
		;
		if( list.size() ==1){
			select.addAttribute("parameterType",list.get(0).getFullyQualifiedJavaType().getLongName());
		}else{
			select.addAttribute("parameterType","map");
		}
		new XmlElement(select,"include").addAttribute("refid", "basefield");
		if(schema.isIncludeBlobColumn()){
			select.addAttribute("resultMap",var_entity_name+mybatisPlugin.getBlobSuffix());
			select.addTextElement(",");
			new XmlElement(select,"include").addAttribute("refid", "blobfield");
		}else{
			select.addAttribute("resultMap",var_entity_name);
		}
		select.addTextElement("FROM "+schema.getName());
		
		addPrimaryKeyConditionElement(select, list,introspectSchemaColumn.allColumns());
		
	}
}
